<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="common/common_head :: commonHeader('采购申请录入')"/>
    <link th:href="@{/static/css/plugins/cropper/cropper.min.css}" rel="stylesheet">
    <link th:href="@{/static/css/custom/jquery.auto-complete.css}" rel="stylesheet">
</head>
<body class="gray-bg">
<div class="wrapper wrapper-content animated fadeInRight">
    <form class="form-horizontal" method="post" id="proPurchRequestHeaderForm">
        <div class="row">
            <div class="form-group">
                <div class="col-sm-8" style="margin-left: 16px">
                    <input class="btn btn-primary" type="button" onclick="save()" value="保存">
                    <button class="btn btn-primary" type="button" onclick="Dialog.closeFrame(window.name)">取 消</button>
                	<div id="fromQuotaView" style="margin-left: 20px;display: none;color: red;"><label>下单顺序:</label><div id="orderList" style="display: inline"></div><div id="applyAndQuota"  style="display: inline;margin-left: 50px"></div></div>
				</div>
            </div>
			<div>
			    <div class="ibox float-e-margins">
	                <div class="ibox-content">
		                <div id="toolbar" class="btn-group">
						    <!--<button type="button" class="btn btn-xs btn-link" onclick="addtr()">添加</button>-->
						</div>
						<div class="table-responsive">
						  <table class="table table-bordered text-nowrap" id="para_table">
						       <thead>
									<tr>
									    <th></th>
									    <th></th>
									    <th>采购申请编码</th>
									    <th>采购申请行项目编码</th>
										<th>信息类别</th>
										<th>供应商编码</th>
										<th>供应商名称</th>
										<th>付款条件</th>
										<th>含税单价</th>
										<th>价格单位</th>
										<th>货币</th>
										<th>税码</th>
										<th>申请数量</th>
										<th>计量单位</th>
										<th>可分配量</th>

									    <th>科目类别</th>
									    <th>采购组</th>
									    <th>采购组织</th>
									    <th>使用人</th>
									    <th>物料号</th>
									    <th>物料描述</th>
									    <th>工厂</th>
									    <th>库存地点</th>
									    <th>物料组</th>
									    <th>成本中心</th>
									    <th>内部订单号</th>
									    <th>主资产号</th>
									    <th>资产次级编号</th>
									    <!-- <th>需求日期</th> -->
									    <th>交货日期</th>
									    <th>交货地址</th>
									    <th>备注</th>

									    <th>信息记录编码</th>
									    <th>操作</th>
									</tr>
								</thead>
								<tbody id="itemStatus" th:class="${isFromQuota}">
								     <tr th:each="EssentialInformationVO,itemStat : ${itemList}" th:class="${itemStat.odd}?'odd':'even'">
								        <!-- <tr th:each="EssentialInformationVO : ${itemlist}"> -->
								        <td><input class="checkStatus" name="pkId" type="radio" th:value="${EssentialInformationVO.pkId}" th:attr="freeze=${EssentialInformationVO.freeze}, infoStatus=${EssentialInformationVO.infoStatus}"/>
											<input  name="quotaId"  th:value="${EssentialInformationVO.quotaId}" style="visibility:hidden;width: 1px;"/></td>
										 <td th:text="${itemStat.index+1}"></td>
								        <td style="display:none"><input disabled  name="pkId" type="hidden" th:value="${EssentialInformationVO.pkId}" /></td>
								        <td width='30px'><input disabled id="purchRequestCode" name='purchRequestCode' th:value="${EssentialInformationVO.purchRequestCode}" /></td>
								        <td width='110px'><input disabled style='width:95%' type='text' name='purchRequestItemCode' th:value="${EssentialInformationVO.purchRequestItemCode}" /></td>
									 	<td width='110px'><select style='width:95%' type='text' th:data-val="${EssentialInformationVO.classify}" sysDict='XXLB' disabled></select></td>
									 	<td width='110px'><input style='width:95%' type='text' name='sapCode' th:value="${EssentialInformationVO.sapCode}" readonly="readonly"/></td>
									 	<td ><input  type='text' name='vendorName' th:value="${EssentialInformationVO.vendorName}" readonly="readonly"/></td>
									 	<td width='110px'><input style='width:95%' type='text' name='payCondition' th:value="${EssentialInformationVO.payCondition}" readonly="readonly"/></td>
									 	<td width='110px'>
											<input type='number' name='price' th:value="${EssentialInformationVO.price}"  th:if="${EssentialInformationVO.price!=0}" readonly/>
											<input type='number' name='price' th:if="${EssentialInformationVO.price==0}"/>
										</td>
									 	<td width='110px'><input style='width:95%' type='text' name='priceUnit' th:value="${EssentialInformationVO.priceUnit}" readonly="readonly"/></td>
									 	<td width='110px'><input style='width:95%' type='text' name='currency' th:value="${EssentialInformationVO.currency}" readonly="readonly"/></td>
									 	<td width='110px'><input style='width:95%' type='text' name='taxCode' th:value="${EssentialInformationVO.taxCode}" /></td>
										 <td width='110px'><input disabled style='width:95%' type='text' name='applyQty' th:value="${EssentialInformationVO.applyQty}" /></td>
										 <td width='110px'><select disabled name='measureUnit' th:data-val="${EssentialInformationVO.measureUnit}" sysDict='JLDW'></select></td>
										 <!-- quotaNum -->
									 	<td width='110px'><input style="width:100px;" type='text' name='quantity' th:value="${EssentialInformationVO.quotaNum!=null?EssentialInformationVO.quotaNum-EssentialInformationVO.usedQuotaNum:EssentialInformationVO.applyQty}" readonly="readonly"/>
											 <input style="width:1px;visibility: hidden;" type='text' name='quotaNum' th:value="${EssentialInformationVO.quotaNum}" readonly="readonly"/>
											 <input style="width:1px;visibility: hidden;" type='text' name='usedQuotaNum' th:value="${EssentialInformationVO.usedQuotaNum}" readonly="readonly"/></td>
									 	<td width='110px'><input disabled style='width:95%' type='text' name='subjectCategory' th:value="${EssentialInformationVO.subjectCategory}"/></td>
								        <td width='110px'><select disabled name='purchGroup' th:data-val="${EssentialInformationVO.purchGroup}" sysDict='CGZ'></select></td>
									    <td width='110px'><select disabled name='purchOrg' th:data-val="${EssentialInformationVO.purchOrg}" sysDict='CGZZ'></select></td>
									    <td width='110px'><input disabled type='text' name='applier' th:value="${EssentialInformationVO.applier}"/></td>
									    <td width='110px'><input disabled type='text' name='materialCode' th:value="${EssentialInformationVO.materialCode}"/></td>
									    <td width='110px'><input disabled type='text' name='materialDesc' th:value="${EssentialInformationVO.materialDesc}" style="width: 300px"/></td>
									    <td width='110px'><select disabled name='factory' th:data-val="${EssentialInformationVO.factory}" sysDict='GC'></select></td>
									    <td width='110px'><input disabled name='storageLocation' th:value="${EssentialInformationVO.storageLocation}" ></td>
									    <td width='110px'><select disabled  name='materialGroup' th:data-val="${EssentialInformationVO.materialGroup}" sysDict='WLZ'></select></td>
									     <!--<td width='110px'><select disabled style='width:95%' name='costCenter' th:data-val="${EssentialInformationVO.costCenter}" sysDict='CBZX'></select></td>-->
									    <td width='110px'><input disabled style='width:95%' name='costCenter' th:value="${EssentialInformationVO.costCenter}" /></td>
									    <td width='110px'><input style='width:95%' type='text' name='internalOrderCode' th:value="${EssentialInformationVO.internalOrderCode}" readonly="readonly"/></td>
									    <td width='110px'><input style='width:95%' type='text' name='mainAssetsCode' th:value="${EssentialInformationVO.mainAssetsCode}" readonly="readonly"/></td>
									    <td width='110px'><input style='width:95%' type='text' name='assetsSencondCode' th:value="${EssentialInformationVO.assetsSencondCode}" readonly="readonly"/></td>
									    <!-- <td width='110px'><input style='width:95%' type='text' name='requestDate' th:value="${EssentialInformationVO.requestDate}" readonly="readonly"/></td> -->
									    <td width='110px'><input  type='text' name='deliveryDate' th:value="${EssentialInformationVO.deliveryDate}" readonly="readonly" style="width: 100px"/></td>
									    <td ><select disabled name='deliveryAddress' sysDict='JHDZ' style="width: 400px;"></select></td>
									    <td width='110px'><input style='width:95%' type='text' name='remark' th:value="${EssentialInformationVO.remark}" readonly="readonly"/></td>
									    <td width='110px'><input style='width:95%' type='text' name='infoCode' th:value="${EssentialInformationVO.infoCode}" readonly="readonly"/></td>
									    <td width='110px'></td>
									    <!-- <td width='30px' align='center' onclick='deletetr(this)'><button type='button' class='btn btn-xs btn-link'>删除</button></td> -->
									  </tr>
								</tbody>
							</table>
						</div>
                    </div>
			</div>
		</div>
      </div>
   </form>
</div>

<!--引入公共js-->
<div th:include="common/onload_js :: onloadJS"></div>
<!-- Chosen -->
<script th:src="@{/static/js/plugins/chosen/chosen.jquery.js}"></script>

<script type="text/javascript">
    
    //动态加载一行
    function addtr() {
		//获取选中的option
		var options=$("#purchRequestType option:selected");
		//拿到选中项的文本
		var purchRequestType = options.text();
		
		//获取选中的option
		var options=$("#purchGroup option:selected");
		//拿到选中项的文本
		var purchGroup = options.val();
		var purchGroupText = options.text();
		
		if(purchRequestType==null||purchRequestType=="undefined"||purchRequestType==""){
			alert("请选中采购申请类型");
			return;
		}
		
		if(purchGroup==null||purchGroup=="undefined"||purchGroup==""){
			alert("请选择采购组");
			return;
		}
		
		var subjectCategory, subjectCategoryText;
		
		if(purchRequestType == 'ZFY-部门费用类申请'){ //ZFY-费用类申请, ZGD-固定资产类申请, ZNB-在建工程类申请
			subjectCategory = 'K';
			subjectCategoryText = 'K-成本中心';
		}else if(purchRequestType == 'ZGD-固定资产类申请'){
			subjectCategory = 'A';
			subjectCategoryText = 'A-固定资产';
		}else if(purchRequestType == 'ZNB-在建工程类申请'){
			subjectCategory = 'F';
			subjectCategoryText = 'F-在建工程';
		}
		
		var mydate = new Date();
		var uuid = "rdn"+mydate.getDay()+ mydate.getHours()+ mydate.getMinutes()+mydate.getSeconds()+mydate.getMilliseconds();//根据时间来自动生成uuid，保证生成的id是唯一的

		var trCode = "<tr>";
	    trCode += "<td width='30px'><input name='purchRequestCode' /></td>";
	    trCode += "<td width='110px'><input style='width:95%' type='text' name='purchRequestItemCode' /></td>";
	    trCode += "<td width='110px'><input style='width:95%' type='text' name='subjectCategory' /></td>";
	    trCode += "<td width='110px'><select style='width:95%' name='purchGroup' dictType='CGZ'></select></td>";
	    trCode += "<td width='110px'><select style='width:95%' name='purchOrg' dictType='CGZZ'></select></td>";
	    trCode += "<td width='110px'><input style='width:95%' type='text' name='usePeople' /></td>";
	    trCode += "<td width='110px'><input style='width:95%' type='text' name='materialDesc' /></td>";
	    trCode += "<td width='110px'><select style='width:95%' name='factory' dictType='GC'></select></td>";
	    trCode += "<td width='110px'><select style='width:95%' name='storageLocation' dictType='KCDD'></td>";
	    trCode += "<td width='110px'><select style='width:95%' name='materialGroup' dictType='WLZ'></select></td>";
	    trCode += "<td width='110px'><input style='width:95%' type='text' name='applyQty' /></td>";
	    trCode += "<td width='110px'><select style='width:95%' name='measureUnit' dictType='JLDW'></td>";
	    trCode += "<td width='110px'><select style='width:95%' name='costCenter' dictType='CBZX'></select></td>";
	    trCode += "<td width='110px'><input style='width:95%' type='text' name='internalOrderCode' /></td>";
	    trCode += "<td width='110px'><input style='width:95%' type='text' name='mainAssetsCode' /></td>";
	    trCode += "<td width='110px'><input style='width:95%' type='text' name='assetsSencondCode' /></td>";
	    trCode += "<td width='110px'><input style='width:95%' type='text' name='requestDate' /></td>";
	    trCode += "<td width='110px'><input style='width:95%' type='text' name='deliveryDate'/></td>";
	    trCode += "<td width='110px'><select style='width:95%' name='deliveryAddress' dictType='JHDZ'></select></td>";
	    trCode += "<td width='110px'><input style='width:95%' type='text' name='remark' /></td>";
	    trCode += "<td width='30px' align='center' onclick='deletetr(this)'><button type='button' class='btn btn-xs btn-link'>"+"删除"+"</button></td>";
	    trCode += "</tr>";
	    $("#para_table tbody").append(trCode);
	    
        // 初始化时间插件
        laydate.render({elem: '#requestDateId'+uuid});
        laydate.render({elem: '#deliveryDateId'+uuid});
        
        //自动往select框里面填充字典数据
		var sels = $("select[dictType]");
		sels.each(function(i, e) {
			e = $(e);
			if(e.attr("filled")=="true") {
				return;
			}
			//通过此属性来回显默认选中的
			var defaultVal = e.attr("data-val");
			if(e.attr("emptyFirst")=="true") {
				e.append("<option value=''></option>");// 添加一个空的option
			}
			//得到此属性的值查询字典表里的文本开回显到下拉框下
			var dictTypeName = e.attr("dictType");
			Page.ajaxGET(ctxPath + "/sys/dict/getDictData", {'dictTypeName':dictTypeName}, function(o) {
				var res = o.result;
				for(var k in res){
					if(defaultVal == k) {
						e.append("<option value='"+k+"' selected>"+res[k]+"</option>");// 添加option
					} else {
						e.append("<option value='"+k+"'>"+res[k]+"</option>");// 添加option
					}
				}
				e.attr("filled", "true")
			}, {
				async : false
			});
		});
    }
    
    function deletetr(tdobject) {
	    var td = $(tdobject);
	    td.parents("tr").remove();
    }


	//是否从配额取数据，配额：true，信息记录：false
	var isFromQuota=false;
    //下单顺序
	orderArr=new Array();
	var allCount=0;
    $(function() {
		//初始化所有字典数据
		initDictDataSel();

    	//判断数据是否来自配额还是信息记录
		isFromQuota=$("#itemStatus").attr('class');
		if(isFromQuota=='true'){
			$(".checkStatus").attr('type','checkbox');
			$("#fromQuotaView").css('display','inline');
			$(".checkStatus").on('click',function(e){
				var applyQty=parseInt($('input[name="applyQty"]').first().val());
				if($(e.currentTarget).is(":checked")){
					//信息记录被冻结，不能选择
					if($(e.currentTarget).attr('freeze')==1){
						Dialog.errorMsg("该信息记录已被冻结不可选择！");
						$(e.currentTarget).attr('checked',false);
						return false;
					}
					//信息记录未确认，不能选择
					if($(e.currentTarget).attr('infoStatus')==0){
						Dialog.errorMsg("该信息记录未确认，不可选择！");
						$(e.currentTarget).attr('checked',false);
						return false;
					}
					//如果当前选择的配额总数大于申请量,则提示不能再选择
					if(applyQty<=allCount){
						Dialog.errorMsg("所选配额总量已大于申请量,不能再选择!");
						$(e.currentTarget).attr('checked',false);
						return;
					}
					//配额量累计
					allCount+=parseInt($(e.currentTarget.parentElement.parentElement).find('input[name="quantity"]').val());
					orderArr.push(e.currentTarget.parentElement.nextElementSibling.innerText);
				}else{
					//配额量累计
					allCount-=parseInt($(e.currentTarget.parentElement.parentElement).find('input[name="quantity"]').val());
					orderArr.splice(orderArr.indexOf(e.currentTarget.parentElement.nextElementSibling.innerText),1);
				}
				//显示下单顺序
				var str='';
				for (var i in orderArr){
					str+=' -> '+orderArr[i];
				}
				$("#orderList").text(str);
				$("#applyAndQuota").text("申请量："+applyQty+"　　累计配额量："+allCount);
			})
		}

	    //抬头
    	$("#purchRequestType").change(function() {
    		
    		var tds = $("#para_table").find("td[name='subjectCategoryText']");
    		var _this = $(this);
    		
    		var checkText=_this.find("option:selected").text();  //获取Select选择的Text
    		var subjectCategory, subjectCategoryText;
    		
			if(checkText == 'ZFY-部门费用类申请'){ //ZFY-费用类申请, ZGD-固定资产类申请, ZNB-在建工程类申请
				subjectCategory = 'K';
				subjectCategoryText = 'K-成本中心';
			}else if(checkText == 'ZGD-固定资产类申请'){
				subjectCategory = 'A';
				subjectCategoryText = 'A-固定资产';
			}else if(checkText == 'ZNB-在建工程类申请'){
				subjectCategory = 'F';
				subjectCategoryText = 'F-在建工程';
			}
    	    //遍历
    		tds.each(function(index, item) {
    			item = $(item);
    			item.find("span[name='subjectCategorySpan']").text(subjectCategoryText);//文本
    			item.find("input[name='subjectCategory']").val(subjectCategory);//隐藏域
    		});
    	});
	    
    	$("#purchGroup").change(function() {
    		//获取选中的option
    		var options=$("#purchGroup option:selected");
    		//拿到选中项的文本
    		var purchGroup = options.val();
    		var purchGroupText = options.text();
    		var tds = $("#para_table").find("td[name='purchGroupText']");
    		var _this = $(this);
    		//通过遍历更新所有的采购组
    		tds.each(function(index, item) {
    			item = $(item);
    			item.find("span[name='purchGroupSpan']").text(purchGroupText);//文本
    			item.find("input[name='purchGroup']").val(purchGroup);//隐藏域
    		});
    	});
    });
    /**
    * 封装并提交数据
    **/
    function save() {
		//判断信息记录是否被冻结
		let freeze = false;
		//判断信息记录是否确认
		let infoStatus = false;
    	var pkIds=$('input[type="radio"]');
    	var priceArr=$('input[name="price"]');
    	for(var i=0;i< pkIds.length;i++){
    		//当前行被选中
    		if(pkIds[i].checked){
				//判断价格是否为数字
				var tsxPrice =priceArr[i].value;
				if(tsxPrice==null||tsxPrice.trim()==''){
					Dialog.errorMsg("请填写价格！");
					return;
				}
			}
		}
    	//2019-06-20----yanfei--/
    	 var purchRequestCode = $("#purchRequestCode").val();
    	 var data = {'isFromQuota':isFromQuota,"purchRequestCodetem" : purchRequestCode, "essentialInformationVO" : []};//先定义数据结构，head是一个对象，item是一个数组
    	 var Tabobj = $("#para_table");
		var Check='';
		//购买量从配额取
		if(isFromQuota!='false'){
			//总申请量
			var applyQty=parseInt($('input[name="applyQty"]').first().val());
			var
			Check=$('.checkStatus:checked');
			if(Check.length==0){
				Dialog.errorMsg("请选择要生成的订单!");
				return;
			}else if(allCount<applyQty){
				Dialog.errorMsg("申请量大于配额量，请继续选择！");
				return;
			}
			for(var i=0;i<Check.length;i++){
				var trs = $(Check[parseInt(orderArr[i])-1]).parent("td").parent("tr");//获取选中行
				var itemEntity = {};
				var essentialInformationVO ={};
				var its = $(trs).find("input, select");
				its.each(function(idx, it) {//循环遍历，把item的内容塞进一个item对象，然后加到数组里
					essentialInformationVO[$(it).attr("name")] = $(it).val();
				});
				//如果申请数量大于剩余配额数,值为零;小于剩余配额量，剩余减去申请量。后台据此设置已用配额
				if(applyQty>=parseInt(essentialInformationVO['quantity'])){
					applyQty-=parseInt(essentialInformationVO['quantity']);
					essentialInformationVO['quantity']=0;
				}else {
					essentialInformationVO['quantity']=parseInt(essentialInformationVO['quantity'])-applyQty;
					applyQty=0;
				}
				if(JSON.stringify(essentialInformationVO) != "{}"){
					itemEntity["essentialInformationVO"] = essentialInformationVO;
				};
				data.essentialInformationVO.push(itemEntity);
			}
		}else{//购买量从信息记录取
			Check = $("table input[type=radio]:checked");//在table中找input下类型为radio属性为选中状态的数据
			Check.each(function () {//遍历
				//信息记录已被冻结
				if($(this).attr('freeze')==1){
					freeze = true;
				}
				//信息记录已未确认
				if($(this).attr('infoStatus')==0){
					infoStatus = true;
				}
				var trs = $(this).parent("td").parent("tr");//获取选中行
				trs.each(function(index, tr) {//循环遍历，把item的内容塞进一个item对象，然后加到数组里
					var itemEntity = {};
					var essentialInformationVO ={};
					var its = $(tr).find("input, select");
					its.each(function(idx, it) {//循环遍历，把item的内容塞进一个item对象，然后加到数组里
						essentialInformationVO[$(it).attr("name")] = $(it).val();
					});
					if(JSON.stringify(essentialInformationVO) != "{}"){
						itemEntity["essentialInformationVO"] = essentialInformationVO;
					};
					data.essentialInformationVO.push(itemEntity);
				});
			});
		}
    	 var arr = data.essentialInformationVO;
    	 if (arr.length == 0){
    		   Dialog.errorMsg("请选择要货源分配的数据");
		 } else if (freeze) {
			 Dialog.errorMsg("该信息记录已被冻结不可选择！");
			 return false;
		 } else if (infoStatus) {
			 Dialog.errorMsg("该信息记录未确认不可选择！");
			 return false;
		 } else {
			 //从配额取值，直接分配货源
			 let url = ctxPath + "/proPurchRequestHeader/updateSource";
			 //从信息记录、货源记录中取数据，先保存分配货源数据，实现批量生成一个订单
			 if (isFromQuota == 'false') {
				 url = ctxPath + "/proPurchRequestHeader/saveDistributeData";
			 }
			 layer.load(1, {shade: [0.3, '#393D49']});
			 $.ajax({
				 type: "POST",
				 url: url,
				 data: JSON.stringify(data),//必须
				 contentType: "application/json;charset=UTF-8",//必须
				 dataType: "json",//必须
				 cache: true,
				 async: true,
				 success: function (res) {
					 layer.closeAll();
					 if (isFromQuota != 'false') {
						 alert("订单号已经生成：" + res["poNo"]);
					 } else {
						 Dialog.msg("操作成功");
					 }
					 parent.refresh();
					 Dialog.closeFrame(window.name);
				 },
				 error: function (request) {
					 layer.closeAll();
					 showTipAlert("Connection error");
				 }
			 });
    	 }
    	/*****************************************************/
    	/*var purchRequestCode = $("#purchRequestCode").val();
    	var data = {"purchRequestCodetem" : purchRequestCode, "essentialInformationVO" : []};//先定义数据结构，head是一个对象，item是一个数组
		//得到行项目数据
		var trs = $("#para_table").find("tr");
		trs.each(function(index, tr) {//循环遍历，把item的内容塞进一个item对象，然后加到数组里
			var itemEntity = {};
			var essentialInformationVO ={};
			var its = $(tr).find("input, select");
			its.each(function(idx, it) {//循环遍历，把item的内容塞进一个item对象，然后加到数组里
				essentialInformationVO[$(it).attr("name")] = $(it).val();
			});
			if(JSON.stringify(essentialInformationVO) != "{}"){
				itemEntity["essentialInformationVO"] = essentialInformationVO;
			}
			data.essentialInformationVO.push(itemEntity);
    	});*/
		 
    }
</script>

</body>
</html>
